﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QLK.Database.DALs
{
    public class CustomerDAL
    {
        private ManageStoreDataContext db;

        public CustomerDAL()
        {
            db = new ManageStoreDataContext();
        }

        public List<Customer> CustomerGetAll()
        {
            var Cus = from cust in db.Customers
                      orderby cust.CustomerName
                      select cust;
            return Cus.ToList<Customer>();
        }

        public Customer CustomerGetByID(int CusID)
        {
            Customer Cus = db.Customers.Single<Customer>(cust => cust.CustomerID == CusID);

            return Cus;
        }

        public bool CustomerInsert(Customer Cust)
        {
            try
            {
                db.Customers.InsertOnSubmit(Cust);
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool CustomerDeleteByID(int CusID)
        {
            Customer Cust = db.Customers.SingleOrDefault<Customer>(cus => cus.CustomerID == CusID);

            if (Cust == null)
                return false;

            db.Customers.DeleteOnSubmit(Cust);

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool CustomerUpdate(Customer Cust)
        {
            Customer custommer = db.Customers.SingleOrDefault<Customer>(cus => cus.CustomerID == Cust.CustomerID);

            if (custommer == null)
                return false;

            custommer.CustomerName = Cust.CustomerName;
            custommer.Address = Cust.Address;
            custommer.PhoneNumber = Cust.PhoneNumber;

            try
            {
                db.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public int CustomerGetIDByName(string CustName)
        {
            Customer Cust = db.Customers.SingleOrDefault<Customer>(c => c.CustomerName.Equals(CustName));

            return Cust.CustomerID;
        }

        public bool CustomerCheckIsNull()
        {
            var Cust = from c in db.Customers
                       select c;
            if (Cust.ToList<Customer>().Count == 0)
                return true;
            else
                return false;
        }
    }
}
